/*
 * GoodsDetailBuyManager.java
 * business
 *
 * Created by SunDing on 2016/12/22.
 *
 * Copyright (c) 2016年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.widget.dialog;

import android.app.Activity;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yidiandao.business.R;
import com.yidiandao.business.data.bean.Goods;
import com.yidiandao.business.data.realm.BrowingHistoryBean;
import com.yidiandao.business.data.response.GoodsDetailResponse;
import com.yidiandao.business.ui.goodsdetail.GoodsDetailContract;
import com.yidiandao.business.ui.widget.view.FavorableLayout;
import com.yidiandao.business.ui.widget.view.GoodsCountMenu;
import com.yidiandao.business.utils.ImageLoader;
import com.yidiandao.business.utils.PreferenceUtils;
import com.yidiandao.business.utils.RealmUtils;
import com.yidiandao.business.utils.UIUtils;

import java.util.List;

import io.realm.Realm;

/**
 * 商品详情的manager
 */
public class GoodsShoppingDialog implements View.OnClickListener {
    private AlertDialog mDialog;
    private ImageView mIvLogo;
    private TextView mTvName;
    private TextView mTvNumber;
    private TextView mTvPrice;
    private GoodsCountMenu mGoodsCountMenu;
    /**
     * 是加入购物车还是购买
     */
    private int mIndex;

    private GoodsDetailContract.Presenter mPresenter;
    /**
     * 商品活动类型
     */
    private int mGoodsType;
    /**
     * 商品id
     */
    private String mGoodsId;
    /**
     * 能否加入购物车
     */
    private boolean mCanCart;

    private Realm historyRealm;
    private Activity mActivity;

    public GoodsShoppingDialog(Activity activity) {
        mActivity = activity;
    }

    public void initBuyDialog(Activity activity) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity, R.style.BottomDialogTheme);
        View view = View.inflate(activity, R.layout.dialog_goods_detail, null);
        builder.setView(view);
        mIvLogo = (ImageView) view.findViewById(R.id.iv_logo);
        mTvName = (TextView) view.findViewById(R.id.tv_name);
        mTvNumber = (TextView) view.findViewById(R.id.tv_number);
        mTvPrice = (TextView) view.findViewById(R.id.tv_price);
        mGoodsCountMenu = (GoodsCountMenu) view.findViewById(R.id.goods_count_menu);

        view.findViewById(R.id.tv_buy_now).setOnClickListener(this);
        view.findViewById(R.id.iv_finish).setOnClickListener(this);
        mDialog = builder.create();
    }

    private void setDialogWindowStyle() {
        // 改变样式-->window的样式
        Window window = mDialog.getWindow();
        if (window != null) {
            WindowManager.LayoutParams params;

            params = window.getAttributes();
            // 设置弹出位置
            params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;

            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;

            window.setAttributes(params);
        }
    }

    /**
     * 设置dialog的数据
     *
     * @param index 是加入购物车或购买
     */
    public void setDialogData(GoodsDetailResponse.DataBean dataBean, int index, GoodsDetailContract.Presenter presenter) {
        mIndex = index;
        mPresenter = presenter;
        Goods goods = dataBean.getGoodsInfo();
        //图片
        ImageLoader.loadImageWithPlaceHolder(UIUtils.getContext(), mIvLogo, goods.getOriginalImg());
        //商品名
        mTvName.setText(goods.getGoodsName());

        //判断是否是直接购买，若是，数量为1 ；不是 设置已经加入购物车的数量
        int num = index == 1 ? goods.getMinNumber() : dataBean.getCartGoodsNumber();
        //库存
        int stockNumber = goods.getStockNumber();
        //抢购商品限购数量
        int limitNumber = goods.getLimitNumber();
        mTvNumber.setText(UIUtils.getString(R.string.goodsdetail_number, stockNumber));
        mGoodsCountMenu.setMaxGoodsCount(limitNumber > 0 ? limitNumber : stockNumber); //设置最大
        mGoodsCountMenu.setMinGoodsCount(goods.getMinNumber());
        // 商品数量为0时,设置为最少起订量
        if (num <= 0) {
            num = goods.getMinNumber();
        }
        mGoodsCountMenu.setGoodsCount(num); //当前数量
        //价格
        mGoodsType = goods.getGoodsType();
        String price =
                goods.getGoodsType() == 0 ? goods.getShopPriceFloat() : goods.getLimitPrice();
        mTvPrice.setText(price);
        //商品id
        mGoodsId = goods.getGoodsId();
        //判断加入购物车，是活动商品  0 不能  1能
        mCanCart = dataBean.getCanCart() != 0;

        showDialog();
    }

    private void showDialog() {
        if (null != mDialog && !mDialog.isShowing()) {
            mDialog.show();
            setDialogWindowStyle();
              /*mDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
            mDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
            //自动弹出软键盘
            mDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
            InputMethodManager imm = (InputMethodManager)
                    mActivity.getSystemService(INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); */
        }
    }

    /**
     * 设置活动说明描述
     */
    public void setActiveDesc(
            GoodsDetailResponse.DataBean dataBean,
            LinearLayout llGoodsPromotion,
            FavorableLayout favorableLayout) {
        GoodsDetailResponse.DataBean.ActivityListBean activityList = dataBean.getActivityList();
        if (activityList != null
                && (activityList.getBouns().size() > 0
                || activityList.getPromotion().size() > 0
                || activityList.getLimitTime().size() > 0
                || activityList.getFree().size() > 0
                || activityList.getSecondKill().size() > 0
                || activityList.getLimitGoods().size() > 0)) {
            llGoodsPromotion.setVisibility(View.VISIBLE);
            List<String> promotion = activityList.getPromotion(); //促销活动
            List<String> bouns = activityList.getBouns(); //红包
            List<String> limitBuy = activityList.getLimitTime(); //限时购
            List<String> free = activityList.getFree(); //免费赠
            List<String> secondKill = activityList.getSecondKill(); //秒杀
            List<String> limitGoods = activityList.getLimitGoods(); //限购
            favorableLayout.setData(promotion, bouns, limitBuy, free, secondKill, limitGoods);
        } else {
            llGoodsPromotion.setVisibility(View.GONE);
        }
    }

    /**
     * 数据存入数据库
     */
    public void insertDataToRealm(Goods goods) {
        if (!PreferenceUtils.STRING_DEFAULT.equals(
                PreferenceUtils.getToken(UIUtils.getContext()))) {
            final BrowingHistoryBean bean = new BrowingHistoryBean();
            bean.setGoods_id(goods.getGoodsId());
            bean.setGoodsImgUrl(goods.getOriginalImg());
            bean.setGoodsName(goods.getGoodsName());
            bean.setPrice(goods.getShopPrice());
            bean.setGoods_brand(goods.getGoodsBrand());
            bean.setUserId(PreferenceUtils.getUserId(UIUtils.getContext()));

            historyRealm = RealmUtils.getHistoryRealm(UIUtils.getContext());
            historyRealm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    //存在就替换，不存在就存储
                    realm.copyToRealmOrUpdate(bean);
                }
            });
        }
    }

    /**
     * 关闭数据库
     */
    public void closeHistoryRealm() {
        // 登陆时才有数据库
        if (null != historyRealm
                && !PreferenceUtils.STRING_DEFAULT.equals(
                PreferenceUtils.getToken(UIUtils.getContext()))) {
            historyRealm.close();
        }
    }

    @Override
    public void onClick(View v) {
        mDialog.dismiss();
        switch (v.getId()) {
            case R.id.tv_buy_now:

                // 修改为最小起订量
                if (mGoodsCountMenu.getGoodsCount() < mGoodsCountMenu.getMinGoodsCount()) {
                    UIUtils.showToast(UIUtils.getString(R.string.min_number, mGoodsCountMenu.getMinGoodsCount()));
                    mGoodsCountMenu.setGoodsCount(mGoodsCountMenu.getMinGoodsCount());
                    return;
                }

                switch (mIndex) {
                    case GoodsDetailResponse.BuyType.CART:
                        // 加入购物车
                        mPresenter.addToCart(mGoodsId, mGoodsCountMenu.getGoodsCount());
                        break;
                    case GoodsDetailResponse.BuyType.BUY:
                        // 立即购买
                        // 普通商品与活动商品接口统一
//                        if (mCanCart) {
//                            //普通商品
                        mPresenter.buyNow(mGoodsId, mGoodsCountMenu.getGoodsCount());
//                        } else {
                        //活动商品
//                        ConfirmOrderActivity.actionStartForActiveGoods(mActivity, mGoodsId, mGoodsCountMenu.getGoodsCount(), mGoodsType);
//                        }
                        break;
                }
                break;
        }
    }
}
